package dataStore.updateDataStoreTaskBag;

import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.sql.SQLException;
import java.sql.Statement;

import dataStruct.DataStoreTask;
import dataStruct.DataStoreTaskBag;
import tool.GetProper;
import tool.MysqlApi;
public class UpdateDataStoreTaskBag extends Thread {
	public UpdateDataStoreTaskBag(
			Queue<DataStoreTask> dataStoreTaskChunkQueue,
			Queue<String> dataStoreTaskSlaverChunkQueue,
			Map<String, DataStoreTaskBag> dataStoreTaskSlaverChunkMap)
	{
		UpdateDataStoreTaskBag.dataStoreTaskChunkQueue = dataStoreTaskChunkQueue;
		
		UpdateDataStoreTaskBag.dataStoreTaskSlaverChunkQueue = 	dataStoreTaskSlaverChunkQueue;
		UpdateDataStoreTaskBag.dataStoreTaskSlaverChunkMap = dataStoreTaskSlaverChunkMap;

		
		masterProper = GetProper.get_properties("conf/config.ini");
		blockCopy = Long.parseLong(masterProper.getProperty("blockCopy"));
	}
	
	public void run()
	{
		while(true)
		{
			try {
				update_task_bag();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private static void update_task_bag() throws SQLException
	{
		while(true)
		{
			DataStoreTask dataStoreTask = dataStoreTaskChunkQueue.poll();
			if(dataStoreTask == null)
				return ;
			
		     Statement state = MysqlApi.get_statement();

		     for(long i = 0; i < blockCopy; ++i)
		     {
		    	 	String slaverChunkId = MysqlApi.insert_slaver_chunk(state, dataStoreTask.chunkId );
		    	 	System.out.println(String.format("****taskId:%s has producted(UpdateDataStoreTask.java)", slaverChunkId));
			
		    	 	DataStoreTaskBag dataStoreTaskBag = new DataStoreTaskBag();
		    	 	dataStoreTaskBag.dataStoreTask = dataStoreTask;
		    	 	dataStoreTaskBag.startTime = new Long(0); //System.currentTimeMillis();
		    	 	dataStoreTaskBag.slaverId = new Integer(0);
		    	 	dataStoreTaskBag.isSlaverDown = false;
		    	 	dataStoreTaskSlaverChunkMap.put(slaverChunkId, dataStoreTaskBag);
		    	 	dataStoreTaskSlaverChunkQueue.offer(slaverChunkId);
		     }
		}
	}
	private static Queue<DataStoreTask> dataStoreTaskChunkQueue;
	private static Map<String, DataStoreTaskBag> dataStoreTaskSlaverChunkMap;
	private static Queue<String> dataStoreTaskSlaverChunkQueue;

	private static Properties masterProper;
	private static Long blockCopy;
}
